$(function() {
	FastClick.attach(document.body);
	window.categories = null;
	window.markets = null;
	window.is_overlay_show = false;
	
	console.log('index');
	
	// load data
	loadData();

	
}());
/**
 * load data
 */
function loadData() {
	
	gloading.start();
	gmarket.get(function(markets) {
		gloading.stop();
		window.markets = markets;
		if(markets.length > 0) {
			var market = markets[0];
			if(window.marketId) {
				market = getMarketById(markets, window.marketId);
			}
			if(market) {
				renderHeader(market);
				renderContent(market);
			}
		}
	}, true);
}

/**
 * 加载菜场下所有蔬菜
 */
function loadCommodities(marketId, callback) {
	ghttp.get('/market/' + marketId + '/items', null, function(resp) {
		if(!resp.success) {
			callback();
			return;
		}
		callback(resp.result);
	});
}

/**
 * 渲染菜场名称
 */
function renderHeader(market) {
	var $name = $('header .location .market-name');
	var $link = $('header .location a');
	var html = [
		'<span class="name" data-v="' + market.marketId + '" >' + market.marketName + '</span>',
		'<span class="change">［切换菜场］</span>'
	].join('');

	$name.html(html);
	$link.attr('href', '/market/map/' + market.marketId);
}
/**
 * 渲染菜分类
 */
function renderCategories() {
	var $el = $($('#category-item-tpl').html());
	var $categories = $('.categories');

	$el.find('.name').text('全部');
	$el.find('img').attr('src', '/icons/icon-all.png');
	$el.attr('onclick', 'onChangeCategory(0)');
	$categories.html($el);
	$('.categories li').addClass('index');
	var i = 1;
	window.categories.forEach(function(item) {
		$el = $($('#category-item-tpl').html());
		$el.addClass('item-' + i);
		$el.find('.name').text(getName(item.typeName));
		$el.find('img').attr('src', getIcon(item.typeName, item.pic));
		$el.find('img').addClass(getIconClass(item.typeName));
		$el.attr('onclick', 'onChangeCategory(' + i + ', "' + item.typeId + '")');
		$categories.append($el);
		i++;
	});

}

/**
 * 渲染菜市场下的所有菜
 */
function renderContent(market) {
	gloading.start();
	// 加载菜
	loadCommodities(market.marketId, function(obj) {
		window.categories = obj.categories;
		renderCategories();
		renderCommodities(0);
		gloading.stop();
	});
}

/**
 * 渲染蔬菜
 */
function renderCommodities(categoryId) {
	var $items = $('.content .items');
	$items.empty();

	window.categories.forEach(function(item) {
		if(categoryId === 0 || item.typeId === categoryId) {
			var commodities = item.commodities;
			commodities.forEach(function(c) {
				var $el = $($('#commodity-item-tpl').html());

				$el.find('a').attr('href', '/commodity/' + c.commodityId + '/type/' + c.typeId + '?name=' + c.commodity + '&price='+getPrice(c.average) + '&cid=' + c.commodityId)
				$el.find('.cimage').css({ 'background-image': g_image(c.commodity) });
				$el.find('.title .name').text(c.commodity);
				$el.find('.price .current').text(getPrice(c.price));
				$el.find('.price .average').text(getPrice(c.average));
				$items.append($el);
			});
		}
	});
	refreshTime();
}


/**
 * 刷新更新时间
 */
function refreshTime() {
	function __format(v) {
		if (v < 10) {
			return '0' + v;
		}
		return v;
	}
	var $time = $('.content footer .time');
	var now = new Date();
	var year = now.getFullYear();
	var month = now.getMonth();
	var date = now.getDate();
	var time1 = new Date(year, month, date, 9, 0, 0);
	var time2 = new Date(year, month, date, 15, 30, 0);

	var v;
	if (now.getTime() < time1) {
		v = time2 - 3600000 * 24;
	} else if (now.getTime() > time1 && now.getTime() < time2) {
		v = time1;
	} else {
		v = time2;
	}
	v = new Date(v);

	$time.text(v.getMonth() + '月' + v.getDate() + '日 ' +
			__format(v.getHours()) + ':' + __format(v.getMinutes()));
	$time.show();
	$('.content footer').show();
}

function getMarketById(markets, id) {
	var market;
	for(var i=0; i<markets.length; i++) {
		if(markets[i].marketId === id) {
			market = markets[i];
			break;
		}
	}
	return market;
}

function getIcon(typeName, pic) {
	if(pic) {
		return pic;
	} else {
		switch(typeName) {
			case '蔬菜': {
				pic = '/icons/icon-vege.png';
				break;
			}
			case '肉类': {
				pic = '/icons/icon-meat.png';
				break;
			}
			case '海鲜': {
				pic = '/icons/icon-fisher.png';
				break;
			}
			default: {
				pic = '/icons/icon-default.png';
				break;
			}
		}
		return pic;
	}
}

function getName(typeName) {
	if(typeName === '海鲜') {
		return '河海鲜';
	}
	return typeName;
}

function getPrice(price) {
	if(price === '0.0元／500克') {
		return '-';
	}
	return price.replace('元／500克', '');
}

function getIconClass(typeName) {
	var cls = '';
	switch(typeName) {
		case '蔬菜': {
			cls = 'vege';
			break;
		}
		case '肉类': {
			cls = 'meat';
			break;
		}
		case '海鲜': {
			cls = 'fisher';
			break;
		}
	}
	return cls;
}

function appendMarketItem(items) {
	var $markets = $('.markets-overlay .markets');
	items.forEach(function(item) {
		var $item = $($('#market-item-tpl').html());
		$item.find('a').attr('href','/market/'+item.marketId);
		$item.find('.name').text(item.marketName);
		$item.find('.distance').text(item.distance);
		if(item.isYc) { // 诚信
			$item.find('.flag').show();
		}
		$markets.append($item);
	});
}

/******************************************************************/
/**
 * 切换菜分类
 */
function onChangeCategory(index, categoryId) {
	var item = $('.categories li');
	if( index==0){
		item.removeClass('index');
		$('.categories li:first').addClass('index');
		renderCommodities(0);
	} else {
		item.removeClass('index');
		item.eq(index).addClass('index');
		renderCommodities(categoryId);
	}

}

/**
 * 切换菜场
 */
function onChangeMarket(e) {
	var $markets = $('.markets-overlay .markets');
	var $overlay = $('.markets-overlay');
	if(window.is_overlay_show) {
		if($(e.target).closest(".inner").length == 0) {
			window.is_overlay_show = false;
			$overlay.hide();
			$('body').css('overflow','auto');
		}
	} else {
		window.is_overlay_show = true;
		var len = $markets.find('li').length;
		$overlay.css({'margin-top': $('body').scrollTop()+50});
		$overlay.show();
		$('body').css('overflow','hidden');
		if(len === 0) {
			appendMarketItem(window.markets);
		}
	}
}

/**
 * 取消搜索
 */
function onCancel() {
	$('.markets-overlay').hide();
}

/**
 * 搜索菜场
 */
function onSearch() {
	var $markets = $('.markets-overlay .markets');
	$markets.empty();
	var result = [];
	var v = $('#search input').val();
	window.markets.forEach(function(item){
		if(item.marketName.indexOf(v) !== -1) {
			result.push(item);
		}
	});
	appendMarketItem(result);
}